package com.example.hotHub.conf;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;


@Configuration
public class ThreadPoolConfig {

    private static final int SIZE_PROCESSOR = Runtime.getRuntime().availableProcessors();

    /**
     * 线程池维护线程的最少数量
     */
    private final int corePoolSize  = SIZE_PROCESSOR + 1;

    /**
     * 线程池维护线程的最大数量
     */
    private final int maxPoolSize  = SIZE_PROCESSOR * 4;

    /**
     * 缓存队列
     */
    private final int queueCapacity = 100;

    /**
     * 允许的空闲时间
     */
    private final Long keepAliveTime = 60L;


    @Bean
    public ExecutorService threadPoolExecutor() {
        return new ThreadPoolExecutor(corePoolSize , maxPoolSize , keepAliveTime  , TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Bean
    public ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(3,
                new BasicThreadFactory.
                        Builder().namingPattern("schedule-pool-%d").daemon(true).build());
    }
}
